import { login, logout, getInfo } from '../../api/User/user'
import { encrypt, decrypt } from '../../utils/encryption'


const user = {
  state: {
    token: localStorage.getItem("token"),
    name: '',
    avatar: ''
  },
    mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
      localStorage.setItem("token",token)
    },
    SET_USERNAME: (state, username) => {
      state.username = username
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    }
  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        login(encrypt(JSON.stringify(userInfo))).then(response => {
          const data = response.data
          commit('SET_TOKEN', data.token)
          commit('SET_USERNAME', data.username)
          commit('SET_AVATAR', data.avatar)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        localStorage.removeItem("token")
        localStorage.removeItem("username")
        localStorage.removeItem("avatar")
        resolve()
      })
    }
  }
}

export default user
